// 接口配置
let baseUrl = process.env.VUE_APP_BASEURL || 'http://接口域名/'
const uploadPresignedUrl = '获取上传签名/get-upload-token'
const batchUploadPresignedUrl = '批量获取上传签名/get-batch-upload-token'
const getFileUrl = '获取文件下载地址/get-file-url'
const postBatchFileUrl = '批量获取文件下载地址/post-batch-file-url'
const headerAuthName = 'token'
const getSignCode = '获取签名随机数(signCode)/sign-code'
const getFileUrlBySign = '获取文件下载地址(signCode)/get-file-url'
const postBatchFileUrlBySign = '批量获取文件下载地址(signCode)/post-batch-file-url'
const secretKey = '密钥(signCode)'

// 接口配置/数字教材CRM,数字教材Client
// const uploadPresignedUrl = 'jsxf-szjc/rs/upload-sign' // 获取上传签名
// const batchUploadPresignedUrl = 'jsxf-szjc/rs/upload-batch-sign' // 批量获取上传签名
// const getFileUrl = 'jsxf-szjc/rs/get-file-url' // 获取文件下载地址
// const postBatchFileUrl = 'jsxf-szjc/rs/post-batch-file-url' // 批量获取文件下载地址
// const headerAuthName = 'token'
// let baseUrl = process.env.VUE_APP_BASEURL || ''
// if (location.host.includes('devlb.jsxfedu.net')) {
//   baseUrl = '//jsxf-gateway-qa.qalb.jsxfedu.com'
// } else if (location.host.includes('crm.haoxuejun.cn')) {
//   baseUrl = '//gw.jsxfedu.com';
// }
// if (!baseUrl.endsWith('/')) { baseUrl += '/' }

// 接口配置/京师书法
// let baseUrl = '';
// if(location.host.indexOf('qa.') > -1) {
// 	baseUrl = '//jsxf-gateway-qa.qalb.jsxfedu.net/sf-base/'
// }else {
// 	baseUrl = '//gw.jsxfedu.com/sf-base/'
// }
// baseUrl = '//jsxf-gateway-qa.qalb.jsxfedu.net/sf-base/'
// const uploadPresignedUrl = 'file-v2/upload-sign'
// const batchUploadPresignedUrl = 'file-v2/get-batch-upload-token'
// const getFileUrl = 'file-v2/get-file-url'
// const postBatchFileUrl = 'file-v2/post-batch-file-url'
// const headerAuthName = 'token'
// const getSignCode = 'signature-access/file-v2/sign-code'
// const getFileUrlBySign = 'signature-access/file-v2/get-file-url'
// const postBatchFileUrlBySign = 'signature-access/file-v2/post-batch-file-url'
// const secretKey = 'pX6aX7sF8qK6lK8bT6'

/**
 * 生成签名（与后端Java的generateSignature方法对应）
 * @param {string} data - JSON字符串格式的请求参数
 * @param {string} signCode - 从后端获取的签名随机数
 * @param {string} secretKey - 前后端约定的密钥（建议通过环境变量注入）
 * @returns {string} Base64编码的HmacSHA256签名
 */
function generateSignature(data, signCode, secretKey) {
  // 1. 按后端格式拼接字符串：data:signCode:secretKey
  const signStr = `${data}:${signCode}:${secretKey}`;
  console.log('加密前的原始字符串：', signStr)
  // 2. 使用HmacSHA256加密
  const hmacSha256 = globalThis.CryptoJS.HmacSHA256(signStr, secretKey);
  // 3. 将加密结果转换为Base64编码
  return globalThis.CryptoJS.enc.Base64.stringify(hmacSha256);
}

export default {
  /**
   * 上传文件到 cos
   * @param {File | String} file File 或 文件的Base64
   * @param {Object} isShare 公有 true 私有 false
   */
  upload(params) {
    let file = params.file;
    let isShare = !!params.isShare;
    if (!file) { return Promise.reject('参数不能为空！') }
    let _this = this;
    return _this.getUploadKey(file, isShare)
      .then((keyInfo) => { // keyInfo:{resourceKey,name,signUrl}
        params.keyInfo = keyInfo;
        return _this.uploadFileByKey(params);
      })
      .catch((error) => {
        return Promise.reject(error);
      })
  },
  uploadFileByKey(params) {
    let file = params.file;
    let keyInfo = params.keyInfo || {};
    let progressCallback = params.progressCallback || null;
    return new Promise((resolve, reject) => {
      // 如果是 base64 字符串，转成 File 对象
      if (typeof file === 'string') {
        file = this.base64ToFile(file);
      }
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status === 200) {
          resolve(keyInfo);
        } else if (this.readyState === 4) {
          reject('文件上传失败！');
        }
      })
      if (progressCallback) {
        xhr.upload.addEventListener('progress', progressCallback);
      }
      xhr.open('PUT', keyInfo.signUrl);
      xhr.setRequestHeader('Content-Type', file.type);
      xhr.send(file);
    })
  },
  // 从服务端获取上传签名信息-单个
  getUploadKey(file, isShare = false) {
    const reqUrl = baseUrl + uploadPresignedUrl;
    const originalName = file.name;
    return new Promise((resolve, reject) => {
      let data = JSON.stringify({
        originalName: originalName,
        share: isShare,
        platform: 'file_cos'
      });
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取上传签名信息失败！');
        }
      });
      xhr.open('POST', reqUrl);
      xhr.setRequestHeader(headerAuthName, window.localStorage.getItem(headerAuthName));
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(data);
    });
  },
  // 从服务端获取上传签名信息-批量
  getBatchUploadKey(fileArr, isShare = false) {
    const reqUrl = baseUrl + batchUploadPresignedUrl;
    const fileNames = [];
    for (let i = 0; i < fileArr.length; i++) {
      fileNames.push(fileArr[i].name);
    }
    return new Promise((resolve, reject) => {
      let data = JSON.stringify({ originalNames: fileNames, share: isShare });
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取上传签名信息失败！');
        }
      });
      xhr.open('POST', reqUrl);
      xhr.setRequestHeader(headerAuthName, window.localStorage.getItem(headerAuthName));
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(data);
    })
  },
  // 批量获取文件下载地址
  getBatchFileUrl(fileNames) {
    const reqUrl = baseUrl + postBatchFileUrl
    if (fileNames.length === 0) { return Promise.resolve([]) }
    return new Promise((resolve, reject) => {
      let data = JSON.stringify({ fileNames: fileNames, expiration: 86400000 });
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取文件下载地址失败！');
        }
      });
      xhr.open('POST', reqUrl);
      xhr.setRequestHeader(headerAuthName, window.localStorage.getItem(headerAuthName));
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(data);
    })
  },
  getFileUrl(fileName, isShare = false) {
    const reqUrl = baseUrl + getFileUrl
    if (!fileName) { return Promise.reject('参数不能为空！') }
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.addEventListener("readystatechange", function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取文件下载地址失败！');
        }
      });
      xhr.open('GET', `${reqUrl}?expiration=86400000&share=${isShare || false}&fileName=${fileName}`);
      xhr.setRequestHeader(headerAuthName, window.localStorage.getItem(headerAuthName));
      xhr.send();
    })
  },
  // 通过签名访问 / 批量获取文件下载地址
  async postBatchFileUrlBySign(fileNames) {
    const reqUrl = baseUrl + postBatchFileUrlBySign
    if (fileNames.length === 0) { return Promise.resolve([]) }
    if (!globalThis.CryptoJS) { return Promise.reject('请引入CryptoJS第三方库后再试！') }
    const signCode = await this.getSignCode();
    const signStr = generateSignature(JSON.stringify(fileNames), signCode, secretKey);
    return new Promise((resolve, reject) => {
      let data = JSON.stringify({ fileNames: fileNames, expiration: 86400000 });
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取文件下载地址失败！');
        }
      });
      xhr.open('POST', reqUrl);
      xhr.setRequestHeader('access-sign', signStr);
      xhr.setRequestHeader('signCode', signCode);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(data);
    })
  },
  // 通过签名访问 / 获取文件下载地址
  async getFileUrlBySign(fileName, isShare = false) {
    const reqUrl = baseUrl + getFileUrlBySign
    if (!fileName) { return Promise.reject('参数不能为空！') }
    if (!globalThis.CryptoJS) { return Promise.reject('请引入CryptoJS第三方库后再试！') }
    const signCode = await this.getSignCode();
    const signStr = generateSignature(fileName, signCode, secretKey);
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.addEventListener("readystatechange", function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取文件下载地址失败！');
        }
      });
      xhr.open('GET', `${reqUrl}?expiration=86400000&share=${isShare || false}&fileName=${fileName}`);
      xhr.setRequestHeader('access-sign', signStr);
      xhr.setRequestHeader('signCode', signCode);
      xhr.send();
    })
  },
  // 通过签名访问 / 获取签名随机数
  getSignCode() {
    const reqUrl = baseUrl + getSignCode
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.addEventListener("readystatechange", function () {
        if (this.readyState === 4 && this.status === 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.message || data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取签名随机数失败！');
        }
      });
      xhr.open('GET', reqUrl);
      xhr.send();
    })
  },
  // base64 转换为 file 类型
  base64ToFile(base64) {
    const arr = base64.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    const suffix = mime.split('/')[1];
    const filename = Date.now() + '.' + suffix;
    return new File([u8arr], filename, { type: mime });
  }
}
